#!/bin/bash
if [ -n "$GITHUB_PROXY" ]; then
    export CONDA_CHANNELS='https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main,https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/r,https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/msys2'
    export PIP_INDEX_URL='https://mirrors.aliyun.com/pypi/simple/'
fi

source "${LMD_BASE_INSTALL_SCRIPT_DIR}/global/alias.sh"

conda config --set show_channel_urls yes

APP_TARGET_DIR_NAME="spark-tts"

export CURRENT_APP_PATH="${LMD_APPS_DIR}/${APP_TARGET_DIR_NAME}"
echo "App Dir: ${CURRENT_APP_PATH}"

cd "$CURRENT_APP_PATH"
python --version
pip --version

if [ -z "$HF_ENDPOINT" ] && [ -n "$HF_MIRROR" ]; then
    export HF_ENDPOINT="$HF_MIRROR"
fi

export GRADIO_TEMP_DIR="$CURRENT_APP_PATH/temp"

PORT_PARAM=""
if [ -n "$SERVER_PORT" ]; then
    PORT_PARAM="--server_port $SERVER_PORT"
fi

CONDA_PREFIX="./venv"
CONDA_ENV_NAME=sparktts

APP_FILE="webui.py"
if [ -f /System/Library/CoreServices/SystemVersion.plist ]; then
    ARCH=$(uname -m)
    echo "macOS system."
    if [ "$ARCH" == "x86_64" ]; then
        echo "Intel-based Mac. device: cpu"
        sed "s/if platform\.system() == \"Darwin\":/if platform\.system() == \"Darwin\" and torch\.backends\.mps\.is_available():/" "webui.py" > "webui2.py"
        APP_FILE="webui2.py"
    fi
fi

env_list=$(conda env list | awk '{print $1}' | grep -v '^#' | grep -v '^base' | grep -v '^ ')
if echo "$env_list" | grep -q "^${CONDA_ENV_NAME}$"; then
    echo "env found '$CONDA_ENV_NAME'"
    # conda run -n $CONDA_ENV_NAME --no-capture-output python webui.py --device 0 "$PORT_PARAM"
    conda run -n $CONDA_ENV_NAME --no-capture-output python $APP_FILE --device 0 $PORT_PARAM
else
    echo "env '$CONDA_ENV_NAME' dose not exist. use ./venv"
    conda run -p $CONDA_PREFIX --no-capture-output python $APP_FILE --device 0 $PORT_PARAM
fi


